package adapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import data.NameConstants;
import data.Silo;

public class HTTPSiloAdapter implements SiloAdapter {

	// Wildcards are # and +

	private String iNetAdress;
	private String port;

	private String connectionStringSourceSiloData;

	private String connectionStringCurrentSiloData;
	private ArrayList<Silo> registratedSilos = new ArrayList<Silo>();

	public HTTPSiloAdapter(String iNetAdress, String port) {
		this.iNetAdress = iNetAdress;
		this.port = port;

		this.connectionStringSourceSiloData = NameConstants.EMPTY_CONNECTION_STRING_SOURCEDATA
				.replaceAll("#", iNetAdress).replace("+", port);

		this.connectionStringCurrentSiloData = NameConstants.EMPTY_CONNECTION_STRING_CURRENT_FILLING
				.replaceAll("#", iNetAdress).replace("+", port);

	}

	// "http://#:+/cgi-bin/data.cgi?cmd=settings"

	public ArrayList<String[]> requestSourceSiloData() {
		ArrayList<String[]> result = new ArrayList<String[]>();
		String line = null;

		try {
			URL test = new URL(this.connectionStringSourceSiloData);
			HttpURLConnection testConnection = (HttpURLConnection) test
					.openConnection();
			testConnection.setRequestMethod("GET");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					testConnection.getInputStream()));

			while ((line = in.readLine()) != null) {
				if (!line.isEmpty()) {
					String[] tmp = line.split("\t");
					result.add(tmp);
				}
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;

	}

	public ArrayList<String[]> requestCurrentSiloData() {
		ArrayList<String[]> result = new ArrayList<String[]>();
		String line = null;

		try {
			URL test = new URL(this.connectionStringCurrentSiloData);
			HttpURLConnection testConnection = (HttpURLConnection) test
					.openConnection();
			testConnection.setRequestMethod("GET");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					testConnection.getInputStream()));

			while ((line = in.readLine()) != null) {
				if (!line.isEmpty()) {
					String[] tmp = line.split("\t");
					result.add(tmp);
				}
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	public String getiNetAdress() {
		return iNetAdress;
	}

	public void setiNetAdress(String iNetAdress) {
		this.iNetAdress = iNetAdress;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public ArrayList<Silo> getRegistratedSilos() {
		return registratedSilos;
	}

}
